import { NextRequest, NextResponse } from 'next/server'
import { userQueries } from '@/lib/database-prisma'
import { getUserFromRequest } from '@/lib/auth-utils'

export async function GET(request: NextRequest) {
  try {
    const userInfo = await getUserFromRequest(request)
    if (!userInfo) {
      return NextResponse.json({ error: '未授权' }, { status: 401 })
    }

    const searchParams = request.nextUrl.searchParams
    const query = searchParams.get('q') || ''

    // 获取所有用户
    const allUsers = await userQueries.getAll.all()
    
    // 如果有搜索关键词，过滤用户
    let users = allUsers
    if (query) {
      users = allUsers.filter((user: any) => 
        user.name.toLowerCase().includes(query.toLowerCase()) ||
        user.email?.toLowerCase().includes(query.toLowerCase())
      )
    }

    // 返回用户列表（不包含敏感信息）
    const safeUsers = users.map((user: any) => ({
      id: user.id,
      name: user.name,
      email: user.email,
      color: user.color,
      avatar: user.avatar
    }))

    return NextResponse.json(safeUsers)
  } catch (error) {
    console.error('搜索用户失败:', error)
    return NextResponse.json({ error: '搜索用户失败' }, { status: 500 })
  }
} 